package com.zwk.edu.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zwk.base.entity.CommonResult;
import com.zwk.base.handler.GuLiException;
import com.zwk.edu.entity.Chapter;
import com.zwk.edu.entity.Video;
import com.zwk.edu.entity.chapter.ChapterVo;
import com.zwk.edu.service.ChapterService;
import com.zwk.edu.service.VideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 课程 前端控制器
 * </p>
 *
 * @author zwk
 * @since 2022-08-22
 */
@RestController
@RequestMapping("/edu/chapter")
@CrossOrigin
public class ChapterController {

    @Autowired
    private ChapterService chapterService;

    @Autowired
    private VideoService videoService;

    // 查询课程大纲列表
    @GetMapping("/getChapterVideo/{courseId}")
    public CommonResult getChapterVideo(@PathVariable("courseId") String courseId){

        List<ChapterVo> chapterVos = chapterService.getChapterVideoByCourseId(courseId);

        return CommonResult.ok().data("allChapterVideo", chapterVos);
    }

    // 添加章节
    @PostMapping("/addChapter")
    public CommonResult addChapter(@RequestBody Chapter chapter){

        boolean result = chapterService.save(chapter);
        if (!result){
            throw new GuLiException(20001, "添加章节失败");
        }

        return CommonResult.ok();
    }

    // 根据id查询章节
    @GetMapping("/getChapterInfo/{chapterId}")
    public CommonResult getChapterInfo(@PathVariable("chapterId") String chapterId){

        Chapter chapter = chapterService.getById(chapterId);

        return CommonResult.ok().data("chapter", chapter);
    }

    // 修改章节
    @PostMapping("/updateChapter")
    public CommonResult updateChapter(@RequestBody Chapter chapter){

        boolean result = chapterService.updateById(chapter);
        if (!result){
            throw new GuLiException(20001, "修改章节失败");
        }

        return CommonResult.ok();
    }

    // 删除
    @DeleteMapping("{chapterId}")
    public CommonResult deleteById(@PathVariable("chapterId") String chapterId){
        // 查询该章节下是否有小节, 有则不能删除
        QueryWrapper<Video> wrapper = new QueryWrapper<>();
        wrapper.eq("chapter_id", chapterId);
        int count = videoService.count(wrapper);
        if (count <= 0){
            boolean result = chapterService.removeById(chapterId);
            if (!result){
                throw new GuLiException(20001, "删除章节失败");
            }
            return CommonResult.ok();
        }
        return CommonResult.error();
    }

}

